import 'dart:async';
import 'package:connectivity_plus/connectivity_plus.dart';
import 'package:flutter/material.dart';
import 'package:heven/widget/button.dart';
import 'package:heven/pages/home/widget/music/song.dart';
import 'package:heven/pages/home/widget/title.dart';
import 'package:heven/api/index.dart';
import 'package:heven/utils/index.dart';
import 'package:provider/provider.dart';
import 'package:heven/state/music.dart';

class MusicWidget extends StatefulWidget {
  const MusicWidget({super.key});

  @override
  State<MusicWidget> createState() => _MusicWidgetState();
}

class _MusicWidgetState extends State<MusicWidget>
    with AutomaticKeepAliveClientMixin {
  var list = [];
  bool _isVip = false;
  late StreamSubscription _subscription = const Stream.empty().listen((_) {});

  @override
  bool get wantKeepAlive => true; // 保持页面状态

  @override
  void initState() {
    super.initState();
    _init();
  }

  @override
  void dispose() {
    _subscription.cancel();
    super.dispose();
  }

  Future<void> _init() async {
    var workStatus = await Common.checkNetworkStatus();
    if (workStatus) {
      _fetchData();
    } else {
      _subscription = Connectivity().onConnectivityChanged.listen((result) {
        if (result != ConnectivityResult.none) {
          _fetchData();
        }
      });
    }
  }

  Future<void> _fetchData() async {
    var uid = await Common.getStorageValue('uid');
    var isExitStr = await Common.getStorageValue('isExit');
    if (uid == null && isExitStr != '1') {
      await refreshToken();
      uid = await Common.getStorageValue('uid');
    }
    print(uid);

    await recommend({
      "uid": uid,
      "sign": Common.generateSign({"uid": uid})
    }).then((value) {
      setState(() {
        list = value['data']['list'] as List;
        print('list====================: $list');
      });
    }).catchError((error) {
      // 处理错误
      print('Error fetching data: $error');
    });
    if (uid != null) {
      getProfile({"uid": uid}).then((value) {
        if (value['status'] == 200) {
          setState(() {
            _isVip = value['data']['is_vip'];
          });
        }
      });
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context); // 保持页面状态
    return Scaffold(
      backgroundColor: const Color(0xFF010101),
      appBar: AppBar(
        toolbarHeight: 50.0,
        backgroundColor: const Color(0xFF010101),
        leadingWidth: 84,
        leading: Padding(
          padding: const EdgeInsets.only(left: 10),
          child: Image.asset(
            'assets/images/heven.png',
            width: 74,
            height: 20,
          ),
        ),
        actions: [
          Offstage(
            offstage: _isVip,
            child: GestureDetector(
              onTap: () async {
                var token = await Common.getStorageValue('token');
                if (token == null) {
                  Navigator.pushNamed(context, '/login/list');
                  return;
                }
                Navigator.pushNamed(context, '/vip');
              },
              child: Container(
                width: 62,
                height: 25,
                margin: const EdgeInsets.only(right: 10),
                padding: const EdgeInsets.fromLTRB(8, 0, 8, 0),
                decoration: BoxDecoration(
                  color: const Color(0xFF484848),
                  borderRadius: BorderRadius.circular(12),
                ),
                child: Row(
                  children: [
                    Image.asset(
                      'assets/images/vip.png',
                      width: 15,
                      height: 14,
                    ),
                    const SizedBox(width: 6),
                    const Text(
                      'VIP',
                      style: TextStyle(
                        color: Colors.white,
                        fontSize: 13,
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  ],
                ),
              ),
            ),
          ),
          Container(
            margin: const EdgeInsets.only(right: 15),
            child: GestureDetector(
              onTap: () async {
                var _isTourist = await Common.getStorageValue('isTourist');
                Navigator.pushNamed(context, '/set',
                    arguments: {"isTourist": _isTourist});
              },
              child: Image.asset(
                'assets/images/set.png',
                width: 21,
                height: 24,
              ),
            ),
          ),
        ],
      ),
      body: Scrollbar(
        child: SingleChildScrollView(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.start,
            children: [
              Stack(
                children: [
                  Container(
                    margin: const EdgeInsets.fromLTRB(32, 0, 32, 0),
                    width: double.infinity,
                    child: Image.asset(
                      'assets/images/bannar.png',
                      width: double.infinity,
                    ),
                  ),
                  // const Positioned(
                  //   bottom: 55,
                  //   left: 0,
                  //   right: 0,
                  //   child: Align(
                  //     child: Text(
                  //       'AI音乐',
                  //       style: TextStyle(
                  //         fontSize: 22,
                  //         color: Colors.white,
                  //         fontWeight: FontWeight.w700,
                  //       ),
                  //     ),
                  //   ),
                  // ),
                  Positioned(
                    bottom: 28,
                    left: 0,
                    right: 0,
                    child: Align(
                      child: Image.asset(
                        'assets/images/ai_music_to_create.png',
                        width: 170,
                        height: 46,
                      ),
                    ),
                  ),
                ],
              ),
              ButtonWidget(
                onTap: () {
                  Navigator.pushNamed(context, '/creation');
                },
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: [
                    Padding(
                      padding: const EdgeInsets.only(top: 5),
                      child: Image.asset(
                        'assets/images/button_icon.png',
                        width: 26,
                        height: 18,
                      ),
                    ),
                    const Text(
                      '开始创作音乐',
                      style: TextStyle(
                        fontSize: 17,
                        color: Color(0xFF000000),
                        fontWeight: FontWeight.bold,
                      ),
                    )
                  ],
                ),
              ),
              const TitleWidget(title: '推荐歌曲'),
              ...list.map((item) {
                return SongWidget(
                  imgUrl: item['image_url'],
                  name: item['title'],
                  subheading: item['tags'],
                  onTap: () {
                    final musicState = context.read<MusicState>();
                    print(musicState.type);
                    print(000000000000);
                    if (musicState.type == 1 || musicState.type == 3) {
                      musicState.setType(2);
                      final convertedList =
                          list.map<Map<String, String>>((item) {
                        // 确保键和值都被转换为 String 类型
                        return item.map<String, String>((key, value) {
                          return MapEntry(key.toString(), value.toString());
                        });
                      }).toList();
                      musicState.setPlaylist(convertedList);
                      final convertedItem =
                          item.map<String, String>((key, value) {
                        return MapEntry(key.toString(), value.toString());
                      });
                      musicState.setCurrentSong(convertedItem);
                      Navigator.pushNamed(context, '/music');
                    } else {
                      if (musicState.currentSong!['id'] ==
                          item['id'].toString()) {
                        Navigator.pushNamed(context, '/music');
                      } else {
                        final convertedItem =
                            item.map<String, String>((key, value) {
                          return MapEntry(key.toString(), value.toString());
                        });
                        musicState.setCurrentSong(convertedItem);
                        Navigator.pushNamed(context, '/music');
                      }
                    }

                    // 跳转到播放页面
                  },
                );
              }).toList(),
              const SizedBox(height: 18),
            ],
          ),
        ),
      ),
    );
  }
}
